﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace QSDesigner
{
    public class WindowManager
    {
        public static void LaunchWindowNewThread<T>(DesignerItem designerItem) where T : CheckerWindow, new()
        {
            var newWindowThread = new Thread(ThreadStartingPoint);
            newWindowThread.SetApartmentState(ApartmentState.STA);
            newWindowThread.IsBackground = true;

            Func<Window> f = delegate
            {
                var win = new T {DesignerItemId = designerItem.ID};
                return win;
            };

            newWindowThread.Start(f);
        }

        private static void ThreadStartingPoint(object t)
        {
            // Create our context, and install it:
            SynchronizationContext.SetSynchronizationContext(
                new DispatcherSynchronizationContext(
                    Dispatcher.CurrentDispatcher));

            var f = (Func<Window>)t;
            var win = f();         

            // When the window closes, shut down the dispatcher
            win.Closed += (s, e) =>
               Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);

            win.Show();

            // Start the Dispatcher Processing
            Dispatcher.Run();
        }
    }
}
